package com.simon.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * Created by changf on 2017/7/10.
 */
public class NioClient implements  Runnable{
    private BlockingQueue<Integer> words;
    private Random random;

    boolean isOver=false;

    public static void main(String[] args) {
        // 多个线程发起Socket客户端连接请求
        for(int i=0; i<10; i++){
            NioClient c = new NioClient();
            c.init();
            new Thread(c).start();
        }
    }


    public void run() {
        SocketChannel channel=null;
        Selector selector=null;
        try{
            channel=SocketChannel.open();

            channel.configureBlocking(false);
            channel.connect(new InetSocketAddress("127.0.0.1",8383));
            selector=Selector.open();
            channel.register(selector, SelectionKey.OP_CONNECT);

            while(!isOver){
                selector.select(1000);
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while(iterator.hasNext()){
                    SelectionKey key = iterator.next();
                    iterator.remove();
                    handleKey(key,channel);

                }

            }





        }catch (Exception e){

        }
    }
    private void handleKey(SelectionKey key,SocketChannel channel)throws Exception{

        if(key.isConnectable()){
            if(channel.isConnectionPending()){
                if(channel.finishConnect()){
                    //链接成功后注册事件
                    key.interestOps(SelectionKey.OP_READ);
                    channel.write(CharsetHelper.encode(CharBuffer.wrap(getWord()+"")));

                }else{

                    key.cancel();
                }


            }
        }else if(key.isReadable()){
            ByteBuffer byteBuffer=ByteBuffer.allocate(128);
            channel.read(byteBuffer);
            byteBuffer.flip();
            CharBuffer charBuffer = CharsetHelper.decode(byteBuffer);
            String answer=charBuffer.toString();
            System.out.println(Thread.currentThread().getId()+"-------"+answer);
            String word=getWord()+"";
            if(word != null){
                channel.write(CharsetHelper.encode(CharBuffer.wrap(word)));
            }
            else{
                isOver = true;
            }



        }



    }

    private void init() {
        words = new ArrayBlockingQueue<Integer>(5);
        try {
            words.put(1);
            words.put(2);
            words.put(3);
            words.put(4);
            words.put(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        random = new Random();
    }

    private int getWord(){
        return words.poll();
    }
}
